package yxy.game.pm2.active.module;

import org.joda.time.DateTime;
import yxy.apple.util.redisson.RedisException;
import yxy.game.pm2.active.ActiveUtil;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.timeline.TimelineModule;

public class ActiveModule_限时礼包_Area extends TimelineModule {

	// bean -------------------------------------------------
	private static final int acttype = 11;

	private int sid;
	private DateTime start;
	private DateTime update;
	private int day;		//第几天

	public int getSid() {
		return sid;
	}
	public void setSid(int sid) {
		this.sid = sid;
	}
	public DateTime getStart() {
		return start;
	}
	public void setStart(DateTime start) {
		this.start = start;
	}
	public DateTime getUpdate() {
		return update;
	}
	public void setUpdate(DateTime update) {
		this.update = update;
	}
	public int getDay() {
		return day;
	}
	public void setDay(int day) {
		this.day = day;
	}
	
	// func --------------------------------------------------

	private static ActiveModule_限时礼包_Area create(int sid) {
		ActiveModule_限时礼包_Area am = new ActiveModule_限时礼包_Area();

		ServerBean sb = ServerBean.get(sid);
		if(sb == null) {
			return null;
		}
		
		DateTime start = sb.getStarttime();

		am.setSid(sid);
		am.setStart(start);
		am.setUpdate(start);
		am.setDay(0);
		am.set();
		return am;
	}

	public void update() {
		int days = ActiveUtil.days(getStart(), DateTime.now()) + 1;
		if(days < 0) {
			return;
		}
		
		if (days > getDay()) {
			try {
				if (tryLock()) {
					setDay(days);
					setUpdate(DateTime.now());
					set();
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			} finally {
				unlock();
			}
		}
	}

	// redis --------------------------------------------------

	static private String key(int sid) {
		return String.format("SID:%s:ACTTYPE:%S", sid, acttype);
	}

	public void set() {
		try {
			setv(key(getSid()), this);
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 获取 ActiveModule_限时礼包_Area
	 * 
	 * @param playerCode
	 * @return
	 */
	static public ActiveModule_限时礼包_Area get(int sid) {
		try {
			ActiveModule_限时礼包_Area module = getv(key(sid));
			if (module == null) {
				module = create(sid);
			}

			if (module == null) {
				return null;
			}

			module.update();
			return module;
		} catch (RedisException e) {
			e.printStackTrace();
		}
		return null;
	}

	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key(getSid()));
	}

}
